<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/15
 * Time: 23:05
 */
namespace app\admin\logic\transfer_driver;
use app\admin\logic\mqlogic\DirectPublisher;
use app\common\model\zbtask\Money;
use think\exception\ValidateException;
use Yansongda\Pay\Pay;


/**
 * 打款上层服务
 */
class Ali extends Base
{
    private static $exchange = 'cache_excache'; //延时队列
    private static $queue = 'cache_queue'; //延时队列
    private static $routeKey = 'cache_queue'; //延时队列
    private $config = [
        'app_id' => '2019032963698743',
        'notify_url' => '',
        'return_url' => '',
        'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1l8yUM6dEtyhF4s8IyZFsVLVgYI36uG4bDOQE/ASgT5Cz1qNObgEkbSsBBDqviJR8CgZz/wlXPnnABGDa82lDVun0wZnr8+AFSGfbEBS99Dp7Fo1Iej0EvPBkyvfFMmZ5jCRO7Vkg5PXVe/C2ptViHWvQ9YAorcFZHlLIIoln0P123ZInHqSlXr6FWTmj6BlpaVeYHsJPKVp11/4gra2PPzZZMROC5afGKPVvYtF3IVcQ33JPMvYOh5mbt/hYLXQSEnr0ej0fM983MmrEu/yqlu1pXArcULVrVdn+ZuCKVH6Sjwi0ZyR53Lq4N2WJwmxMo/XjmzrdYjrkDwVyCAPtQIDAQAB',
        // 加密方式： **RSA2**
        'private_key' => 'MIIEoQIBAAKCAQEAhDYn9uiwEm+az2gbeCahAAkel4lJnhM/A0rI0kX7+IZvDlWVJMMAWTcr2iQ1AVgwEwdJbZOYDf2fKy9HeyU0R+6te2+3O4d1h/quZz9EsmSuKezP0IXS+4g2K1EVaRdXiD5wiZCS5QZFEcJSueVmjgkDzDIumJ3cAcUmyb0mM76a1ECbp8cWxrkYmOO7P0YjGCklBtBxrZmDwEivwUqLOLDYVinczWiXk5uinPpvCqpx1WEz21nTzUKahc/xN6s9wWI+uuYqWnIDR5Qt8FrWNHV4KcRbQIGfE3qxlLF9mwgGsuJ1tKUy1lO29LDIZaXvF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8OYOdRwvl5LRm0gPaJFMtkuzGF2xtCEuc6qUsNJE/I35TpHjDFXc2HdtROIhJqXog+rsBxHuLrGwo16K3TdE8yoiKLnFSA2oxWGPk4vVSEujVL59Uua1Jk9XWmGNKb+nB6xtHAOwAjiC55jV6CZY859C+S9QKWA==',
        'log' => [ // optional
            'file' => './logs/alipay.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
       // 'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
    ];
    private static $new; //申请一个私有的静态成员变量来保存该类的唯一实例
    private function __construct()
    {

    }

    public static function instance () { //声明一个静态公共方法，供外部获取唯一实例
        if (!(self::$new instanceof self)) {
            self::$new = new self;
        }
        return self::$new;
    }
    /*$id众包费id*/
    public function pay($id)
    {
        $money = $this->getMoney($id);
        $user = $this->getUser($money['user_id']);
        $order = [
            'out_biz_no' => $money['order_sn'],
            'payee_type' => 'ALIPAY_LOGONID',
            'payee_account' => $money['bank_card'],
            'amount' => $money['get_money'],
            'payee_real_name' => $user['real_name'],
            'remark' => '众包费'
        ];
        try {
            $alipay = Pay::alipay($this->config)->transfer($order);
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
        $alipay = $alipay->toArray();
        if (!$alipay || $alipay['msg'] !== 'Success') {
            throw new ValidateException('支付失败');
        }
        //$money['order_sn'] 订单号
        $this->publisher($money['order_sn'], 1);  //把订单查询加入延时队列
        return $alipay;
    }

    /**
     * 直连交换机
     */
    public function publisher($order_sn, $type) {
        $objMq = new DirectPublisher(config('site.rabitmqconfig'));
        $objMq->setExchange(self::$exchange)->setQueue(self::$queue)->setBindKey(self::$routeKey);
        $objMq->bindDelay();
        $message = json_encode([
            'order_sn' => $order_sn,  //order_sn
            'type'  => $type
        ]);
        $objMq->publish($message);
    }
    public function query($order) {
        if (!$order) {
            throw new ValidateException('参数传递失败');
        }
        $result = Pay::alipay($this->config)->find($order, 'transfer');
        $moneyInfo = Money::get(['order_sn' => $order]);
        if ($result === false) {
            $this->log($moneyInfo, 1, '查询订单失败:' .$result->fail_reason , '支付宝打款');
            throw new ValidateException('查询失败');
        }
        $resultCode = $result->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            if ($result->status == 'SUCCESS') {
                $this->lineNotify($moneyInfo['id'], true);
                $this->log($moneyInfo, 1, '打款成功', '支付宝打款');
            } else if($result->status == 'FAIL') {
                $this->lineNotify($moneyInfo['id'], false);
                $this->log($moneyInfo, 1, '打款失败:' .$result->fail_reason , '支付宝打款');
            } else {
                //其他情况正在处理中  重新加入延时队列处理
                $this->publisher($order, 1);
            }

        } else {
            $this->lineNotify($moneyInfo['id'], false);
            $this->log($moneyInfo, 1, '打款失败:' .$result->msg , '支付宝打款');
        }

        return true;
    }
}